import { RegClass } from "../core/serialize";
import AppNode from "../core/app_node.ts";
import { EleDiv, EleInput } from "../core/data_ext.ts";
import { ProtocolC2SEnterRoom, ProtocolC2SLeaveRoom, ProtocolC2SNewRoom, ProtocolC2STickMsg, ProtocolC2STotalMsg, ProtocolObjectRoom, ProtocolS2CEnterRoom, ProtocolS2CLeaveRoom, ProtocolS2CUpdateRoom } from "../protocol_dist.ts";
import SocketCtrl from "./socket_ctrl.ts";
import { Sync } from "../core/utils.ts";

@RegClass("RoomItem")
export default class RoomItem extends AppNode {
    ebRoomId: EleInput = null;
    lbState: EleDiv = null;
    msg: EleDiv = null;
    room: ProtocolObjectRoom = null;
    async onLoad() {
        await Sync.DelayTime(0.1);
        SocketCtrl.ins.addListener(ProtocolS2CEnterRoom, this.onEnterRoom, this);
        SocketCtrl.ins.addListener(ProtocolS2CLeaveRoom, this.onLeaveRoom, this);
        SocketCtrl.ins.addListener(ProtocolS2CUpdateRoom, this.onUpdateRoom, this);
    }
    onEnterRoom(msg: ProtocolS2CEnterRoom) {
        this.room = msg.room;
        this.refresh();
    }
    onLeaveRoom(msg: ProtocolS2CLeaveRoom) {
        this.room = null;
        this.refresh();
    }
    onUpdateRoom(msg: ProtocolS2CUpdateRoom) {
        this.room = msg.room;
        this.refresh();
    }
    refresh() {
        if (this.room) {
            this.lbState.innerText = `房间(${this.room.id}) 用户数:(${this.room.userList.length})`;
        }
        else {
            this.lbState.innerText = "未进入房间";
        }

        this.msg.style.display = !!this.room ? "flex" : "none";
    }
    onClickNewRoom() {
        if (this.room) {
            return;
        }
        let msg = new ProtocolC2SNewRoom();
        SocketCtrl.ins.sendMessage(msg);
    }
    onClickEnterRoom() {
        if (this.room) {
            return;
        }
        let id = Number(this.ebRoomId.value);
        if (isNaN(id)) {
            return;
        }
        let msg = new ProtocolC2SEnterRoom();
        msg.id = id;
        SocketCtrl.ins.sendMessage(msg);

    }
    onClickLeaveRoom() {
        let msg = new ProtocolC2SLeaveRoom();
        SocketCtrl.ins.sendMessage(msg);
    }
    onClickSendTestData() {
        if (!this.room) {
            return;
        }
        let msg = new ProtocolC2STickMsg();
        msg.time = Date.now();
        msg.data = "123";
        SocketCtrl.ins.sendMessage(msg);
    }
    onClickSendTestDataTotal() {
        if (!this.room) {
            return;
        }
        let msg = new ProtocolC2STotalMsg();
        msg.time = Date.now();
        msg.data = "[123,123,123,123,123,123,123,123]"
        SocketCtrl.ins.sendMessage(msg);
    }
};